package com.example.ddns4j.controller;

import com.aliyun.alidns20150109.Client;
import com.aliyun.alidns20150109.models.*;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.java.Log;
import okhttp3.Connection;
import org.slf4j.Logger;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@PropertySource("classpath*:config.yml")
@ConfigurationProperties
@Data
@Log
public class DDNSTask {
    private String server_username;
    private String server_password;
    private String domain_name;
    private String[] rr_key_word;
    private String current_ip;
    private String hostname;


    private void getCurrentHostIP() {
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        try {
            InetAddress[] adds = InetAddress.getAllByName(hostname);
            current_ip = ((InetAddress) Arrays.stream(adds).filter((ele) -> {
                String str = ele.getHostAddress();
                return str.contains(":") && !str.contains("%");
            }).findFirst().get()).getHostAddress();
        } catch (UnknownHostException var2) {
            var2.printStackTrace();
        }
    }

    /**
     * <pre>
     * 每分钟检查一次变化，查询一次阿里域名，比对本地IP地址。如有变化立刻更新。
     * 注意：阿里云域名解析服务的数据下发频率是10min一次，理论上最多需延迟10分钟。
     * 经半年测试，多数在数分钟内即可生效。偶发阿里云记录更新后互联网不同步问题，再次更新一个新地址冲刷即可。
     * 只要阿里云记录被更新，本DDNS服务程序即生效。</pre>
     */
    @Scheduled(fixedRate=1000*60)
    public void method() throws Exception {
//        获取最新ip地址
        getCurrentHostIP();
        System.out.println(this);
//        配置登录信息
        Config config = new Config();
        config.accessKeyId = server_username;
        config.accessKeySecret = server_password;


//        创建链接
        Client client = new Client(config);
//        配置查询参数
        DescribeDomainRecordsRequest describeDomainRecordsRequest = new DescribeDomainRecordsRequest();
        describeDomainRecordsRequest.setDomainName(domain_name);
//        搜索dns解析列表
        DescribeDomainRecordsResponse describeDomainRecordsResponse = client.describeDomainRecords(describeDomainRecordsRequest);
        List<DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord> record = describeDomainRecordsResponse.getBody().getDomainRecords().getRecord();
//        比对配置清单

        record.forEach((ele)->{
            try {
            }catch (Exception e){
                e.printStackTrace();
            }
            for (String rr : rr_key_word) {
//                配置清单匹配的解析
                if(ele.getRR().equalsIgnoreCase(rr)){
//                    排除不需要更新的解析
                    if(ele.value.equals(current_ip))break;
//                    建立更新解析请求
                    UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest();
                    updateDomainRecordRequest.recordId = ele.recordId;
                    updateDomainRecordRequest.RR = ele.RR;
                    updateDomainRecordRequest.value = current_ip;
                    updateDomainRecordRequest.type = ele.type;
                    try {
//                        更新ip地址
                        UpdateDomainRecordResponse updateDomainRecordResponse = client.updateDomainRecord(updateDomainRecordRequest);
                        log.info("id:"+ele.recordId+" | rr:"+ele.RR +" | value:"+current_ip);
                    } catch (Exception e) {
                    }
                    break;
                }
            }
        });
    }


}
